package com.r2coding.music.aop;

import com.alibaba.fastjson.JSON;
import com.r2coding.music.annotation.SysLog;
import com.r2coding.music.to.LogEntity;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationDetails;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

/**
 * @author:98k灬
 * @since:2022/05/27 18:34
 **/
@Aspect
@Component
public class LogAspect {
    private static final String SUCCESS = "成功";
    private static final String ERROR = "失败";

    @Autowired
    @Lazy
    RabbitTemplate rabbitTemplate;

    @Pointcut("@annotation(com.r2coding.music.annotation.SysLog)")
    public void pointcut() {}

    @Around("pointcut()")
    public Object around(ProceedingJoinPoint joinPoint) throws IOException {
        // 封装日志信息
        LogEntity log = new LogEntity();
        Object result = null;
        try {
            long beginTime = System.currentTimeMillis();
            // 获取方法签名
            MethodSignature signature = (MethodSignature) joinPoint.getSignature();
            // 获取方法
            Method method = signature.getMethod();
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            // 获取用户信息
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails)authentication.getDetails();
            Map<String, Object> map = (Map<String, Object>)details.getDecodedDetails();
            Map<String, Object> userInfo = (Map<String, Object>)map.get("userInfo");
            Integer userId = (Integer)userInfo.get("userId");
            String userName = (String) userInfo.get("username");

            // 设置当前操作用户的用户id
            log.setUserId(userId);
            // 设置当前操作用户的用户名称
            log.setUserName(userName);
            // 设置当前操作用户的用户ip
            log.setIpAddr(getIpAddress(request));

            // 获取方法上面的注解
            SysLog annotation = method.getAnnotation(SysLog.class);
            if (annotation != null) {
                // 设置模块
                log.setModule(annotation.module().getDesc());
                // 设置操作类型
                log.setOperationType(annotation.operationType().getDesc());
                // 设置描述信息
                log.setDescription(annotation.description());
            }
            // 执行代理方法
            result = joinPoint.proceed();
            long time = System.currentTimeMillis() - beginTime;
            log.setTime(Long.toString(time));
            log.setResult(SUCCESS);
        } catch (Throwable e) {
            log.setResult(ERROR);
            e.printStackTrace();
        } finally {
            // 设置操作时间
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            log.setCreateTime(sdf.format(new Date()));
            // 保存日志信息 rabbitMq异步记录日志信息
            String logInfo = JSON.toJSONString(log);
            rabbitTemplate.convertAndSend("IBlog_Log","iblog.log", logInfo);
        }
        return result;
    }

    // 获取请求注解的ip地址
    public static String getIpAddress(HttpServletRequest request) throws IOException {
        // 获取请求主机IP地址,若是经过代理进来，则透过防火墙获取真实IP地址
        String ip = request.getHeader("X-Forwarded-For");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            if (ip == null || ip.length() == 0
                    || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("Proxy-Client-IP");
            }
            if (ip == null || ip.length() == 0
                    || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("WL-Proxy-Client-IP");
            }
            if (ip == null || ip.length() == 0
                    || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("HTTP_CLIENT_IP");
            }
            if (ip == null || ip.length() == 0
                    || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("HTTP_X_FORWARDED_FOR");
            }
            if (ip == null || ip.length() == 0
                    || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getRemoteAddr();
            }
        } else if (ip.length() > 15) {
            String[] ips = ip.split(",");
            for (String s : ips) {
                if (!("unknown".equalsIgnoreCase((String) s))) {
                    ip = s;
                    break;
                }
            }
        }
        return ip;
    }

    /**
     * 获取ip地址
     *
     * @param request
     * @return
     */
    public static String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("X-Real-IP");
        if (ip != null && !"".equals(ip) && !"unknown".equalsIgnoreCase(ip)) {
            return ip;
        }
        ip = request.getHeader("X-Forwarded-For");
        if (ip != null && !"".equals(ip) && !"unknown".equalsIgnoreCase(ip)) {
            int index = ip.indexOf(',');
            if (index != -1) {
                return ip.substring(0, index);
            } else {
                return ip;
            }
        } else {
            return request.getRemoteAddr();
        }
    }

}
